package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.img;
import com.ruoyi.system.domain.imgBrowse;
import com.ruoyi.system.service.ImgBrowseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片浏览控制层
 */
@Controller
@RequestMapping("/system/imgBrowse")
public class imgBrowseController extends BaseController {

    private String prefix = "other/imgBrowse";

    @Autowired
    private ImgBrowseService imgBrowseService;

    @RequiresPermissions("system:user:imgBrowseListView")
    @GetMapping()
    public String user(ModelMap map) throws IOException {
        SysUser user = getSysUser();
        List<imgBrowse> imgBrowseList = imgBrowseService.findUploadImagePathByUserId(user.getUserId().toString());
        //图片路径 + D：
        List<String> list = new ArrayList();
        for (imgBrowse li : imgBrowseList) {
            list.add(li.getImageCompressPath());
        }
        //图片路径
        List<img> pathList = new ArrayList();
        img im = null;
        for (int i = 0; i < list.size(); i++) {
            im = new img();
            String imageString;
            int width;
            int height;
            File file = new File(list.get(i));
            Image src = ImageIO.read(file);
            width = src.getWidth(null);
            height = src.getHeight(null);
            //设置图片流
            BufferedImage tag = new BufferedImage(width / 2, height / 2, BufferedImage.TYPE_INT_RGB);
            //绘制缩小后的图
            tag.getGraphics().drawImage(src, 0, 0, width / 2, height / 2, null);
//            tag.getGraphics().drawImage(src,0,0,width,height,null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(tag, "png", baos);

            String data = DatatypeConverter.printBase64Binary(baos.toByteArray());
            imageString = "data:image/png;base64," + data;

            im.setImg(imageString);
            im.setImgId(imgBrowseList.get(i).getUpId());

            pathList.add(im);
        }
        map.put("pathList", pathList);
        return prefix + "/imgBrowse";
    }

//    @RequiresPermissions("system:user:imgBrowseList")
//    @GetMapping()
//    public String imgBrowse(ModelMap mmap) throws Exception{
//
//        List<imgBrowse> imgBrowseList = imgBrowseService.findUploadImagePathByUserId("8e6d98b90472283cc732220472dccf36");
//        //图片路径 + D：
//        List<String> list = new ArrayList();
//        for (imgBrowse li:imgBrowseList) {
//            String hz = li.getImagePath().substring(li.getImagePath().lastIndexOf("."));
//
//            if(StringUtils.equals(hz,".jpg") || StringUtils.equals(hz,".png") || StringUtils.equals(hz,".jpeg") || StringUtils.equals(hz,".pdf") || StringUtils.equals(hz,".gif") || StringUtils.equals(hz,".WEBP")){
//                list.add("D:"+li.getImagePath());
//            }
//        }
//        //图片路径
//        List<String> pathList = new ArrayList();
//        for(int i =0;i< list.size();i++){
//            String imageString;
//            int width;
//            int height;
//            File file  = new File(list.get(i));
//            Image src = ImageIO.read(file);
//            width = src.getWidth(null);
//            height = src.getHeight(null);
//            //设置图片流
//            BufferedImage tag  = new BufferedImage(width/2,height/2,BufferedImage.TYPE_INT_RGB);
//            //绘制缩小后的图
//            tag.getGraphics().drawImage(src,0,0,width/2,height/2,null);
////            tag.getGraphics().drawImage(src,0,0,width,height,null);
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            ImageIO.write(tag, "png", baos);
//
//            String data = DatatypeConverter.printBase64Binary(baos.toByteArray());
//            imageString = "data:image/png;base64," + data;
//            pathList.add(imageString);
//        }
//        mmap.put("pathList",pathList);
//
//        return prefix + "/imgBrowse";
//    }

    @PostMapping("/downFile")
    public void downFile(HttpServletResponse response, HttpServletRequest request) throws Exception {
        try {
            File file = new File("D:\\uploadImagePath\\2022-06-21\\cd01db8eebdb434ca4fa66fca12fbcc2_1.png");
//            File file = new File("F:\\BaiduNetdiskDownload\\activiti教程 (1).pdf");
            String filename = file.getName();
            String fileType = filename.substring(filename.indexOf(".") + 1);

            // 以流的形式下载文件。
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[1024];
            int len = 0;
            // 清空response
            response.reset();
            // 设置response的Header
            // 解决跨域
//            response.addHeader("Access-Control-Allow-Origin", "*");
            boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
            // 图片预览
            if (b) {
                response.setContentType("image/" + fileType);
            } else if ("pdf".equalsIgnoreCase(fileType)) {
                // pdf 预览
                response.setContentType("application/pdf");
            } else {
                // 直接下载
                response.setContentType("application/text;chartset=utf-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                response.addHeader("Content-Length", "" + file.length());
            }
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            int a = 0;
            while ((len = fis.read(buffer)) != -1) {
                a = len + a;
                toClient.write(buffer, 0, len);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}
